#!/bin/sh
# mount the usb stick in a specific directory and archive
# it when unmounting.

# TODO
#	- Finish implimenting restore and new
#	- Better error handling
#	- Rotate backups

bak_dir="${HOME}/arc"
bak_host='user@trusted.lan:arc'
enc_host='user@untrusted.net:arc'

case "$1" in
	'sdy')
		dsk_id='b70ca4dea25c4679.a'
		mnt_dir="${HOME}/sdy"
		bak_file="Study-`date "+%y%m%d%M%S"`.tar.gz"
	;;
	'dat')
		dsk_id='.a'
		mnt_dir="${HOME}/dat"
		bak_file="Data-`date "+%y%m%d%H%M%S"`.tar.gz"
	;;
	'snd')
		dsk_id='.a'
		mnt_dir="${HOME}/snd"
		bak_file="Music-`date "+%y%m%d%H%M%S"`.tar.gz"
	;;
	'img')
		dsk_id='e5c3fc7e2c093e38.a'
		mnt_dir="${HOME}/img"
		bak_file="Photos-`date "+%y%m%d%H%M%S"`.tar.gz"
	;;
	*)
		echo "usage: $0 [complex things here]" 
		exit
	;;
esac

mnt() {
	printf 'Mounting on %s\n' "$mnt_dir"
	doas mount "$dsk_id" "$mnt_dir"
	mount | grep "$mnt_dir"
	echo ''
	df -h "$mnt_dir"
}

umnt() {
	printf 'Unmounting disk\n'
	doas umount "$dsk_id" && rm -rf "$mnt_dir"
}

bak() {
	printf 'Writing backup to %s/%s\n' "$bak_dir" "$bak_file"
	cd "$mnt_dir"
	tar -czf "${bak_dir}/${bak_file}" ./
	du -h "${bak_dir}/${bak_file}"
}

rbak() {
	scp "${bak_dir}/${bak_file}" "${bak_host}/${bak_file}"
}

new() {
	# unfinished, unconfigured, never ran..
	# blanks a usb stick with new single ffs sd2a
	# need to copy disklabel for restore
	printf 'Device name? [sd2]: '
	read new_dsk
	if [ "$opt" = '\n' ] ; then
		new_disk='sd2'
	fi
	doas fdisk -i "$new_dsk"
	doas disklabel -E "$new_dsk" # label (e), create (a), save (w)
	doas newfs "${new_dsk}a"
}


enc_bak() {
	cd "$bak_dir"
	openssl enc -aes-256-cbc -in "${bak_file}" -out "${bak_file}.enc"
	# gpg2 --output "${bak_file}.gpg" --symmetric "${bak_file}"
	du -h "${bak_dir}/${bak_file}.enc"
}

dec_bak() {
	cd "$bak_dir"
	openssl enc -d -aes-256-cbc -in "${bak_file}.enc" -out "${bak_file}"
	# gpg2 --output "${bak_file}" --decrypt "${bak_file}.gpg" 
}


if [ "$(mount | grep "$mnt_dir")" = '' ] ; then
	if [ -d "$mnt_dir" ] ; then
		printf 'Mount point %s exists. Ok? ' "$mnt_dir" && read opt
	else
		mkdir "$mnt_dir"
	fi
	mnt
else
	printf 'Create backup? [Y/n]: ' && read opt
	if [ "$opt" != 'n' ] ; then
		bak
		printf 'Send backup to remote host? [Y/n]: ' && read opt
		if [ "$opt" != 'n' ] ; then
			rbak
		fi
		printf 'Encrypt backup? [Y/n]: '
		read opt
		if [ "$opt" != 'n' ] ; then
			enc_bak
			printf 'Send encrypted backup to remote host? [Y/n]: ' && read opt
			if [ "$opt" != 'n' ] ; then
				bak_file="${bak_file}.enc"
				bak_host="$enc_host"
				rbak
			fi
		fi
	fi
	umnt
fi


